package com.mantru.iotpot.dishes

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.distinctUntilChanged
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.mantru.iotpot.Adapter.DishesImageAdapter
import com.mantru.iotpot.R
import com.mantru.iotpot.Util.ToastUtils
import com.mantru.iotpot.databinding.ActivityDishesCreateImageBinding
import android.util.Log

class DishesCreateImageActivity : AppCompatActivity() {
    private val viewModel by viewModels<DishesCreateImageViewModel>()
    private lateinit var binding: ActivityDishesCreateImageBinding
    //adapter属于UI层，负责交互，留在Activity
    private var dishesImageAdapter: DishesImageAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_dishes_create_image)
        binding.viewModel = viewModel // 绑定viewModel
        binding.lifecycleOwner = this // 允许 LiveData 自动更新 UI

        //初始化recyclerview
        setRecyclerView()
        //设置控件交互事件
        setContentAction()
        //观察者模式，观察dishesList变化，更新adapter数据
        setupObservers()
    }

    override fun onResume() {
        super.onResume()
        //获取初始共享照片列表，此时内容为空
        val map: MutableMap<String, Any> = HashMap()
        viewModel.getHttpValue("GetShareImage", map)
    }

    //初始化recyclerview
    private fun setRecyclerView(){
        dishesImageAdapter = DishesImageAdapter(this, R.layout.adapter_dishes_picture, viewModel.dishesList.value ?: mutableListOf())
        binding.dishesImageRecyclerview.apply {
            setLayoutManager(StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL))
            adapter = dishesImageAdapter
        }
    }

    //设置控件交互事件
    private fun setContentAction(){

        // 开启对 foodSearch 的监听
        viewModel.startListeningToPictureSearch()

        //监听输入框回车按键
        binding.dishesImageEdittext.setOnEditorActionListener { v: TextView, actionId: Int, event: KeyEvent? ->
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_NEXT
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEND) {

                // 获取输入法管理器
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
                // 隐藏软键盘
                imm?.hideSoftInputFromWindow(v.windowToken, 0)

                //这里当作搜索处理，那就视为重新加载
                viewModel.page_count = 0
                viewModel.pageStart = 1
                viewModel.searchName = ""

                val map: MutableMap<String, Any> = HashMap()
                viewModel.getHttpValue("GetShareImage", map)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }

        //清空按钮
        binding.dishesImageClear.setOnClickListener {
            viewModel.imageSearch.set("")
        }

        //搜索按钮
        binding.dishesImageSearch.setOnClickListener {
            //如果点击搜索，那就视为重新加载
            viewModel.page_count = 0
            viewModel.pageStart = 1
            viewModel.searchName = ""

            val map: MutableMap<String, Any> = HashMap()
            viewModel.getHttpValue("GetShareImage", map)
        }

        //取消按钮
        binding.dishesImageCancel.setOnClickListener {
            finish()
        }

        //和adapter交互
        dishesImageAdapter!!.setDishesImageListener(object : DishesImageAdapter.DishesImageListener{
            override fun onClick(position: Int) {
                //这里新增返回逻辑，点完就回去了
                val resultIntent = Intent()
                resultIntent.putExtra("vegetableImage",
                    viewModel.face_image_urlList.get()!![position]
                )
                setResult(RESULT_OK, resultIntent)
                finish()
            }
        })

        // 添加滚动监听器
        binding.dishesImageRecyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                // 获取StaggeredGridLayoutManager
                val layoutManager = recyclerView.layoutManager as StaggeredGridLayoutManager
                // 获取当前最后一个可见项的位置
                val lastVisibleItemPositions = IntArray(layoutManager.spanCount)
                layoutManager.findLastVisibleItemPositions(lastVisibleItemPositions)

                // 找出最大的最后一个可见项位置
                val lastVisibleItemPosition = lastVisibleItemPositions.maxOrNull() ?: 0
                // 获取总的数据量
                val totalItemCount = layoutManager.itemCount

                // 判断是否滑动到了底部
                if (!recyclerView.canScrollVertically(1) && lastVisibleItemPosition == totalItemCount - 1) {
                    //如果数据未加载完，则进一步加载数据，否则不加载
                    if ( viewModel.pageStart < viewModel.page_count ){
                        //因为继续请求，pageStart的数量加1
                        viewModel.pageStart++

                        val map: MutableMap<String, Any> = HashMap()
                        viewModel.getHttpValue("GetShareImage", map)
                    }
                }
            }
        })
    }

    //观察者模式，观察dishesList变化，更新adapter数据
    private fun setupObservers() {
        viewModel.dishesList
            .distinctUntilChanged() // 过滤相同数据
            .observe(this) { list ->
                list?.let {
//                    dishesImageAdapter?.updateData(it)
                    // 这里判断是否是第一次加载，如果是第一次加载则全部更新，之后只追加
                    if (viewModel.pageStart == 1) {
                        dishesImageAdapter?.updateData(it)
                    } else {
                        dishesImageAdapter?.addData(it)
                    }
                }
            }
    }
}